package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-mgmts/cache"
	"novel-mgmts/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var art []model.Article
	redis_key := "redis_error" + strconv.Itoa(page)
	js, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if js == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&art)
		jsonData, _ := json.Marshal(art)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(js), &art)

	}
	var total int64
	model.DB.Model(&model.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  400,
		"msg":   "展示成功",
		"data":  art,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	title := c.Query("title")
	var art model.Article
	redis_key := "redis_" + title + "_article"
	js, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if js == "" {
		model.DB.Where("title =?", title).Debug().Find(&art)
		jsonData, _ := json.Marshal(art)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(js), &art)

	}
	var total int64
	model.DB.Model(&model.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  400,
		"msg":   "展示成功",
		"data":  art,
		"total": total,
	})
	return

}
